<?php
namespace Cyfy\Modules\PHPMailer;

require_once('PHPMailer_v5.1/class.phpmailer.php');

class PHPMailer extends \PHPMailer
{
	private $template = "Cyfy/Modules/PHPMailer/mails/default.tpl.php";
	private $content, $blocks;
    
    public function __construct()
    {
        $email = \Cyfy\Constants :: get("SiteInformation", "email");
        if($email)
        {
            $this -> setFrom(\Cyfy\Constants :: get("SiteInformation", "email"), \Cyfy\Constants :: get("SiteInformation", "name"));
        }
        else
        {
            $this -> setFrom("username@email.com");    
        }
    }
    
    
    public function setSubject($subj)
    {
        $this -> Subject = $subj;
    }
    
    
	public function setTemplate($module, $file)
	{
		$filename = "templates/" . \Cyfy\Cyfy :: $template . "/mails/" . $file . ".tpl.php";
        
		if(file_exists($filename))
		{
			$this -> template = $filename;    
			return true;
		}
    
		$filename = "Cyfy/Modules/" . $module . "/mails/" . $file . ".tpl.php";
		if(file_exists($filename))
		{
			$this -> template = $filename;    
			return true;
		}
    
		return false;
	}
	
	public function setContent($content)
	{
        $this -> content = $content;
	}
	
	public function post()
	{
        // utf
        $this -> CharSet = "utf-8";
    
        // content
        if(is_array($this -> content))
        {
            $this -> blocks = $this -> content;
        }
        else
        {
            $this -> blocks["content"] = $this -> content;
        }
        
        // add to the message
        $this -> MsgHTML($this -> loadFile());
        
        try{
            $snt = $this -> Send();
            \Cyfy\Log :: write("Email sent");
            return $snt;
        }catch(Exception $e)
        {
            \Cyfy\Log :: writeError("Sending email failed.");
            return false;
        }
	}
	
	protected function block($code){
		return $this -> blocks[$code];
	}	
		
	private function loadFile(){
		return include_once($this -> template);
	}

	static public function IsValid($email){
		return filter_var($email, FILTER_VALIDATE_EMAIL);
	}  
}